package com.xzz.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: hhz
 * @createDate: 2021-4-16
 */
public class PrintABCUsingWaitNotify {
    private int n;
    private int state;
    private static final Object LOCK = new Object();

    public PrintABCUsingWaitNotify(int n) {
        this.n = n;
    }
    private void printName(String name, int targetState) {
        for (int i = 0; i < n; i++) {
            synchronized (LOCK) {
                while (state % 3 != targetState) {
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                state++;
                System.out.print(name);
                LOCK.notifyAll();
            }
        }
    }
    public static void main(String[] args) {
        PrintABCUsingWaitNotify usingLock = new PrintABCUsingWaitNotify(100);
        new Thread(() -> {
            usingLock.printName("A", 0);
        }, "A").start();
        new Thread(() -> {
            usingLock.printName("B", 1);
        }, "B").start();
        new Thread(() -> {
            usingLock.printName("C", 2);
        }, "C").start();

    }

}
